package com.discuz.spider;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Set;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;


public class Login {
	
	private static String URL = "http://www.jpvip.net";
	private static String FORM_XPATH ="//*[@id='lsform']";
	private static String U_INPUT_XPATH="username";
	private static String P_INPUT_XPATH="password";
	private static String U="only";
	private static String P="19830207Yang";
	private static String LOGIN_BUTTON_XPATH = "//*[@id='lsform']/div/div/table/tbody/tr[2]/td[3]/button";
	

	
	
	
	public  static HtmlPage login() throws Throwable, MalformedURLException, IOException{
	   
		int ret = 1;
		WebClient client = WebClientAgent.get();
		
		
	    HtmlPage page = client.getPage(URL);
	    HtmlForm form = page.getFirstByXPath(FORM_XPATH);
	    HtmlInput u = form.getInputByName(U_INPUT_XPATH);
	    HtmlInput p = form.getInputByName(P_INPUT_XPATH);
	    
	    u.blur();
	    u.setValueAttribute(U);
	    
	    p.blur();
	    p.setValueAttribute(P);
	   
	    HtmlButton btn = page.getFirstByXPath(LOGIN_BUTTON_XPATH);
	    HtmlPage homePage =  btn.click();
	    
	    String ctx = homePage.asText();
	    
	    if(ctx.contains("登录失败")){
	    	System.out.println("login failed");
	    	ret = 2;
	    }else if(ctx.contains("设置")){
	    	
	    	System.out.println("login succeedful");
	    	ret = 3;
	    	//save cookie
	    }else{
	    	ret = 4;
	    	System.out.println("login no");
	    }
	    
	    return homePage;
	}

}
